﻿using System;
using System.Windows.Input;
using System.Diagnostics;

namespace myLiveMesh.ViewModels
{
    public interface ICommandManager
    {
        event EventHandler _requerySuggested;
    }

    public class relayCommand : ICommand
    {
        #region Fields

        readonly Action<object> _execute;
        readonly Predicate<object> _canExecute;
        readonly ICommandManager _commandManager;

        #endregion

        #region Constructors

        public relayCommand(Action<object> execute):
            this (execute, null, null)
        {
        }

        public relayCommand(Action<object> execute, ICommandManager commandManager):
            this (execute, null, commandManager)
        {
        }

        public relayCommand(Action<object> execute, Predicate<object> canExecute, ICommandManager commandManager)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");
            this._execute = execute;
            this._canExecute = canExecute;
            this._commandManager = commandManager;
        }

        #endregion

        #region ICommand Members

        [DebuggerStepThrough]
        public bool CanExecute(object parameter)
        {
            return this._canExecute == null ? true : this._canExecute(parameter);
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                if (this._commandManager != null)
                    this._commandManager._requerySuggested += value;
            }
            remove
            {
                if (this._commandManager != null)
                    this._commandManager._requerySuggested -= value;
            }
        }

        public void Execute(object parameter)
        {
            this._execute(parameter);
        }

        #endregion
    }
}
